package cn.itcast.nems.manager.weixin;

import cn.itcast.nems.manager.redis.RedisUtil;
import cn.itcast.nems.manager.util.OkHttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * author liyong
 * create: 2024-03-20 11:03:11
 **/
public class WeixinManager {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final static String CACHE_KEY_PRE = "NEMS:WEIXIN:";
    private RedisUtil redisUtil;
    private final String webhookKey;
    private final String webhookApi = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send";
    private final ObjectMapper objectMapper = new ObjectMapper();

    public WeixinManager(String webhookKey) {
        this.webhookKey = webhookKey;
    }

    /**
     * 发送markdown格式消息
     *
     * @param key     消息关键（可以区分2个不同消息）属性，根据该属性重复的key一定时间内不会重发
     * @param message markdown格式消息内容
     */
    public void sendMarkdownMessage(String key, String message) {
        if (this.preSend(key)) {
            String webhookUrl = String.format("%s?key=%s", webhookApi, webhookKey);
            final ObjectNode json = objectMapper.createObjectNode();
            json.put("msgtype", "markdown");
            ObjectNode markdown = objectMapper.createObjectNode();
            markdown.put("content", message);
            json.put("markdown", markdown);
            String response = OkHttpUtil.doPost(webhookUrl, json.toString());
            logger.debug("webhook send response: {}", response);
            this.postSend(key);
        }else{
            logger.debug("消息 key: '{}' 10分钟之内发过", key);
        }
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    private boolean preSend(String key) {
        boolean result = true;
        if (this.redisUtil != null) {
            String cacheKey = this.getCacheKey(key);
            result = !this.redisUtil.hasKey(cacheKey);
        }
        return result;
    }

    private void postSend(String key) {
        if (this.redisUtil != null) {
            String cacheKey = this.getCacheKey(key);
            try {
                this.redisUtil.set(cacheKey, Boolean.TRUE, RedisUtil.ONE_DAY);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String getCacheKey(String key) {
        return CACHE_KEY_PRE + key;
    }
}
